// 报警处理 Web Worker
// 专门处理设备状态报警，避免影响主线程性能

interface AlarmData {
  deviceId: string;
  deviceName: string;
  sensorType: string;
  sensorIndex: number;
  value: number;
  actualValue?: number; // 新增：存储报警时的实际数值
  timestamp: number;
  message: string;
  gatewayIp?: string; // 新增：网关IP
  gatewayName?: string; // 新增：网关名称
  // 新增：状态持续期统计数据
  firstAlarmTime?: number; // 首次报警时间
  lastUpdateTime?: number; // 最后更新时间
  maxValue?: number;       // 报警期间的最大值
  minValue?: number;       // 报警期间的最小值
  alarmCount?: number;     // 报警次数统计
  duration?: number;       // 持续时间（毫秒）
}

interface DeviceStatus {
  ID: string;
  data: number[]; // 实际传感器数值
  sta: number[]; // [温度, 湿度, 压力, 红外, 紫外] 状态值
  gatewayIp?: string; // 网关IP
  gatewayName?: string; // 网关名称
}

interface AlarmConfig {
  enabled: boolean;
  voiceEnabled: boolean;
  threshold: number; // 报警阈值，默认为1
  cooldownTime: number; // 报警冷却时间（毫秒），避免频繁报警
}

// 传感器类型映射
const SENSOR_TYPES = {
  0: { name: '温度', unit: '°C', icon: '🌡️' },
  1: { name: '湿度', unit: '%', icon: '💧' },
  2: { name: '压力', unit: 'Pa', icon: '📊' },
  3: { name: '红外', unit: '°C', icon: '🔴' },
  4: { name: '紫外', unit: '', icon: '☀️' }
};

// 全局配置
let alarmConfig: AlarmConfig = {
  enabled: true,
  voiceEnabled: true,
  threshold: 1,
  cooldownTime: 30000 // 30秒冷却时间
};

// 新增：存储模块ID到名称的映射
const moduleNameMap = new Map<string, string>();

// 传感器状态跟踪
interface SensorState {
  isAlarming: boolean;        // 当前是否在报警状态
  alarmStartTime: number;     // 报警开始时间
  lastPushTime: number;       // 最后一次推送到列表的时间
  lastPushMaxValue: number;   // 最后一次推送时的最大值
  currentMaxValue: number;    // 当前周期的最大值
  currentAlarmData: AlarmData; // 当前报警周期的数据
  lastDataTime: number;       // 最后收到数据的时间
}

// 传感器状态映射：网关IP_设备ID_传感器索引 → 状态
const sensorStates = new Map<string, SensorState>();
// 活跃报警列表（用于UI显示）
const activeAlarms = new Map<string, AlarmData>();
// 当前设备数据缓存，用于获取实际数值
const deviceDataCache = new Map<string, number[]>();
// 报警历史记录（用于统计，可选保留）
const alarmHistory = new Map<string, number>();

// 语音播报队列和节流控制
interface VoiceQueueItem {
  message: string;
  priority: number; // 优先级，数字越小优先级越高
  timestamp: number;
}

const voiceQueue: VoiceQueueItem[] = [];
let isVoicePlaying = false;
let voiceThrottleTimer: number | null = null;
const VOICE_THROTTLE_INTERVAL = 3000; // 语音播报间隔3秒
const MAX_QUEUE_SIZE = 5; // 最大队列长度，防止积压过多


/**
 * 添加语音播报到队列
 */
function addToVoiceQueue(message: string, priority: number = 1): void {
  if (!alarmConfig.voiceEnabled) return;

  // 检查队列是否已满
  if (voiceQueue.length >= MAX_QUEUE_SIZE) {
    // 移除最旧的低优先级消息
    const lowPriorityIndex = voiceQueue.findIndex(item => item.priority > 1);
    if (lowPriorityIndex !== -1) {
      voiceQueue.splice(lowPriorityIndex, 1);
    } else {
      // 如果都是高优先级，移除最旧的
      voiceQueue.shift();
    }
  }

  // 添加新消息到队列
  voiceQueue.push({
    message,
    priority,
    timestamp: Date.now()
  });

  // 按优先级和时间排序
  voiceQueue.sort((a, b) => {
    if (a.priority !== b.priority) {
      return a.priority - b.priority; // 优先级低的数字排在前面
    }
    return a.timestamp - b.timestamp; // 时间早的排在前面
  });

  // 尝试处理队列
  processVoiceQueue();
}

/**
 * 处理语音播报队列
 */
function stopAndClearVoice(): void {
  voiceQueue.length = 0; // 清空队列
  if (voiceThrottleTimer) {
    clearTimeout(voiceThrottleTimer);
    voiceThrottleTimer = null;
  }
  isVoicePlaying = false;
  // 通过发消息到主线程来停止当前语音
  self.postMessage({ type: 'stop_speech' });
}

function processVoiceQueue(): void {
  if (isVoicePlaying || voiceQueue.length === 0) {
    return;
  }

  // 清除之前的定时器
  if (voiceThrottleTimer) {
    clearTimeout(voiceThrottleTimer);
    voiceThrottleTimer = null;
  }

  // 设置节流定时器
  voiceThrottleTimer = setTimeout(() => {
    if (voiceQueue.length > 0) {
      const voiceItem = voiceQueue.shift()!;
      isVoicePlaying = true; // 标记为正在播放

      // 发送语音播报请求到主线程
      self.postMessage({
        type: 'voice_alarm',
        message: voiceItem.message,
        priority: voiceItem.priority
      });
      // 注意：不再使用setTimeout来估算结束时间，而是等待主线程的 'voice_ended' 消息
    }
  }, VOICE_THROTTLE_INTERVAL);
}


/**
 * 生成报警唯一标识
 */
function generateAlarmKey(deviceId: string, sensorIndex: number, gatewayIp?: string): string {
  return `${gatewayIp || 'unknown'}_${deviceId}_${sensorIndex}`;
}

/**
 * 生成增强报警消息 - 包含最大值信息
 */
function generateEnhancedAlarmMessage(deviceId: string, sensorIndex: number, actualValue: number | undefined, maxValue: number | undefined, gatewayName?: string, gatewayIp?: string): string {
  const sensor = SENSOR_TYPES[sensorIndex as keyof typeof SENSOR_TYPES];
  if (!sensor) return `设备${deviceId}传感器异常`;
  
  const nameKey = `${gatewayIp}-${deviceId}`;
  // 改进容错处理，确保不会出现undefined
  const deviceName = moduleNameMap.get(nameKey) || `监测点${deviceId}`;
  console.log(`设备名称映射: ${nameKey} -> ${deviceName}`);

  // 添加调试日志，但只在映射未找到时输出
  if (!moduleNameMap.get(nameKey)) {
    console.warn(`设备名称映射未找到: ${nameKey}, 当前映射数量: ${moduleNameMap.size}`);
  }
  
  const gatewayInfo = gatewayName ? `${gatewayName}的` : '';
  const currentValueString = (actualValue !== undefined && actualValue !== null) ? `当前：${actualValue}${sensor.unit}` : '当前数值未知';
  const maxValueString = (maxValue !== undefined && maxValue !== null) ? `最大：${maxValue}${sensor.unit}` : '';

  // 如果有最大值且与当前值不同，则显示最大值信息
  const valueInfo = maxValue !== undefined && maxValue !== actualValue && maxValue > (actualValue || 0)
    ? `${currentValueString}，${maxValueString}`
    : currentValueString;
  console.log(`${gatewayInfo}${deviceName}的${sensor.name}传感器报警！${valueInfo}`)
  return `${gatewayInfo}${deviceName}的${sensor.name}传感器报警！${valueInfo}`;
}

/**
 * 推送报警到列表（包含最大值信息）
 */
function pushAlarmToList(alarmKey: string, deviceId: string, deviceName: string, sensorIndex: number, statusValue: number, actualValue: number | undefined, maxValue: number, gatewayIp: string, gatewayName: string): void {
  const currentTime = Date.now();

  // 创建报警数据
  const alarmData: AlarmData = {
    deviceId,
    deviceName,
    sensorType: SENSOR_TYPES[sensorIndex as keyof typeof SENSOR_TYPES]?.name || '未知传感器',
    sensorIndex,
    value: statusValue,
    actualValue: actualValue,
    timestamp: currentTime,
    gatewayIp: gatewayIp,
    gatewayName: gatewayName,
    message: generateEnhancedAlarmMessage(deviceId, sensorIndex, actualValue, maxValue, gatewayName,gatewayIp),
    // 统计数据
    firstAlarmTime: currentTime,
    lastUpdateTime: currentTime,
    maxValue: maxValue,
    minValue: actualValue || 0,
    alarmCount: 1,
    duration: 0
  };

  // 发送报警通知到主线程（推送到报警列表）
  self.postMessage({
    type: 'alarm_triggered',
    data: alarmData
  });

  // 语音播报
  if (alarmConfig.voiceEnabled) {
    const priority = sensorIndex === 3 || sensorIndex === 4 ? 0 : 1;
    addToVoiceQueue(alarmData.message, priority);
  }

  // 保存报警日志
  self.postMessage({
    type: 'save_alarm_log',
    data: {
      deviceId: alarmData.deviceId,
      sensorType: alarmData.sensorType,
      sensorIndex: alarmData.sensorIndex,
      value: alarmData.value,
      actualValue: alarmData.actualValue,
      message: alarmData.message,
      timestamp: alarmData.timestamp,
      gatewayIp: alarmData.gatewayIp,
      gatewayName: alarmData.gatewayName,
      customName: deviceName, // 添加设备自定义名称
      level: 'error'
    }
  });

  console.log(`[AlarmWorker] 推送报警到列表: ${alarmKey}, 当前值: ${actualValue}, 最大值: ${maxValue}`);
}

/**
 * 结束报警周期
 */
function endAlarm(alarmKey: string): void {
  const sensorState = sensorStates.get(alarmKey);
  if (!sensorState || !sensorState.isAlarming) return;

  const currentTime = Date.now();
  const alarmData = sensorState.currentAlarmData;

  // 计算最终持续时间
  alarmData.duration = currentTime - (alarmData.firstAlarmTime || currentTime);

  // 清理状态
  sensorState.isAlarming = false;
  activeAlarms.delete(alarmKey);

  // 保留状态一段时间用于统计，或者立即删除
  // sensorStates.delete(alarmKey);

  console.log(`[AlarmWorker] 结束报警周期: ${alarmKey}, 持续时间: ${alarmData.duration}ms, 最大值: ${alarmData.maxValue}, 总次数: ${alarmData.alarmCount}`);
}

/**
 * 处理设备状态数据 - 混合策略：30秒冷却期 + 最大值比较
 */
function processDeviceStatus(deviceStatus: DeviceStatus): void {
  try {
  if (!alarmConfig.enabled) {
    return;
  }
  const { ID: deviceId, sta, data, gatewayIp, gatewayName } = deviceStatus;

  // 增加对 deviceId 的有效性检查
  if (!deviceId) {
    console.warn('收到的设备状态中 deviceId 为 undefined，已忽略:', deviceStatus);
    return;
  }

  const currentTime = Date.now();

  // 缓存设备数据
  if (data && data.length > 0) {
    deviceDataCache.set(deviceId, data);
  }
  // 检查每个传感器状态
  sta.forEach((statusValue, sensorIndex) => {
    const alarmKey = generateAlarmKey(deviceId, sensorIndex, gatewayIp);
    let actualValue = data && data[sensorIndex] !== undefined ? data[sensorIndex] : statusValue;

    // 紫外报警时，actualValue取data中的最大值
    if (sensorIndex === 4 && Array.isArray(data) && data.length > 0) {
      actualValue = Math.max(...data);
    }

    // 获取当前传感器状态
    let currentSensorState = sensorStates.get(alarmKey);

    if (statusValue === alarmConfig.threshold) {
      // 设备处于报警状态
      if (!currentSensorState) {
        // 首次报警：创建新的传感器状态并推送到列表
        currentSensorState = {
          isAlarming: true,
          alarmStartTime: currentTime,
          lastPushTime: currentTime,
          lastPushMaxValue: actualValue || 0,
          currentMaxValue: actualValue || 0,
          currentAlarmData: {} as AlarmData, // 临时占位
          lastDataTime: currentTime
        };

        sensorStates.set(alarmKey, currentSensorState);
        alarmHistory.set(alarmKey, currentTime);

        const nameKey = `${gatewayIp}-${deviceId}`;
        const deviceName = moduleNameMap.get(nameKey) || `监测点 ${deviceId}`;

        // 推送首次报警到列表
        if (!actualValue) return
        pushAlarmToList(
          alarmKey,
          deviceId,
          deviceName,
          sensorIndex,
          statusValue,
          actualValue,
          actualValue || 0,
          gatewayIp || '',
          gatewayName || ''
        );

        console.log(`[AlarmWorker] 首次报警: ${alarmKey}, 值: ${actualValue}`);

      } else {
        // 持续报警状态
        currentSensorState.lastDataTime = currentTime;

        // 更新当前最大值
        if (actualValue !== undefined && actualValue !== null) {
          currentSensorState.currentMaxValue = Math.max(currentSensorState.currentMaxValue, actualValue);
        }

        // 检查是否需要推送新的报警到列表
        const shouldPush = shouldPushNewAlarm(currentSensorState, actualValue, currentTime);

        if (shouldPush) {
          const nameKey = `${gatewayIp}-${deviceId}`;
          const deviceName = moduleNameMap.get(nameKey) || `监测点 ${deviceId}`;
          // 推送新的报警到列表
          pushAlarmToList(
            alarmKey,
            deviceId,
            deviceName,
            sensorIndex,
            statusValue,
            actualValue,
            currentSensorState.currentMaxValue,
            gatewayIp || '',
            gatewayName || ''
          );

          // 更新推送记录
          currentSensorState.lastPushTime = currentTime;
          currentSensorState.lastPushMaxValue = currentSensorState.currentMaxValue;

        }
      }

    } else {
      // 设备处于正常状态
      if (currentSensorState && currentSensorState.isAlarming) {
        // 从报警状态转为正常状态：发送恢复通知并清理状态
        // const nameKey = `${gatewayIp}-${deviceId}`;
        // const deviceName = moduleNameMap.get(nameKey) || `监测点 ${deviceId}`;
        
        // self.postMessage({
        //   type: 'alarm_cleared',
        //   data: {
        //     deviceId,
        //     sensorType: SENSOR_TYPES[sensorIndex as keyof typeof SENSOR_TYPES]?.name || '未知传感器',
        //     sensorIndex,
        //     clearedAt: currentTime,
        //     gatewayIp: gatewayIp || '',
        //     gatewayName: gatewayName || '',
        //     maxValue: currentSensorState.currentMaxValue,
        //     message: `${SENSOR_TYPES[sensorIndex as keyof typeof SENSOR_TYPES]?.icon || ''} ${gatewayName ? `${gatewayName}的` : ''}${deviceName}的${SENSOR_TYPES[sensorIndex as keyof typeof SENSOR_TYPES]?.name || '传感器'}状态已恢复正常（最大值：${currentSensorState.currentMaxValue}）`
        //   }
        // });

        // 清理状态
        currentSensorState.isAlarming = false;
        activeAlarms.delete(alarmKey);

        console.log(`[AlarmWorker] 报警恢复: ${alarmKey}, 最大值: ${currentSensorState.currentMaxValue}`);
      }
    }
  });
  } catch (error) {
    console.error(`[AlarmWorker] 处理设备状态数据出错: ${error}`);
  }
}

/**
 * 判断是否应该推送新的报警到列表
 * 策略：首次报警立即推送，后续只在峰值点（数值开始下降时）推送最大值报警
 */
function shouldPushNewAlarm(sensorState: SensorState, currentValue: number | undefined, currentTime: number): boolean {
  // 条件1：30秒冷却期已过
  const cooldownPassed = (currentTime - sensorState.lastPushTime) >= alarmConfig.cooldownTime;

  // 条件2：检测峰值点 - 当前值小于最大值且最大值比上次推送的最大值更大
  const isPeakDetected = currentValue !== undefined && 
                        currentValue < sensorState.currentMaxValue && 
                        sensorState.currentMaxValue > sensorState.lastPushMaxValue;

  // 满足任一条件就推送
  if (cooldownPassed) {
    console.log(`[AlarmWorker] 冷却期已过，重置推送: 距离上次推送 ${Math.round((currentTime - sensorState.lastPushTime) / 1000)}秒`);
    return true;
  }

  if (isPeakDetected) {
    console.log(`[AlarmWorker] 检测到峰值点，推送最大值报警: 当前值=${currentValue}, 最大值=${sensorState.currentMaxValue}, 上次推送最大值=${sensorState.lastPushMaxValue}`);
    return true;
  }

  // 记录数值变化但不推送
  if (sensorState.currentMaxValue > sensorState.lastPushMaxValue) {
    console.log(`[AlarmWorker] 数值持续增长，等待峰值点: 当前值=${currentValue}, 最大值=${sensorState.currentMaxValue}`);
  }

  return false;
}

/**
 * 获取当前活跃报警列表
 */
function getActiveAlarms(): AlarmData[] {
  return Array.from(activeAlarms.values());
}

/**
 * 清理过期的报警历史记录
 */
function cleanupAlarmHistory(): void {
  const currentTime = Date.now();
  const expireTime = 24 * 60 * 60 * 1000; // 24小时

  for (const [key, timestamp] of alarmHistory.entries()) {
    if (currentTime - timestamp > expireTime) {
      alarmHistory.delete(key);
    }
  }
}

/**
 * 清理长时间无活动的传感器状态
 */
function cleanupInactiveStates(): void {
  const currentTime = Date.now();
  const inactiveTimeout = 5 * 60 * 1000; // 5分钟无数据更新视为无效

  for (const [key, sensorState] of sensorStates.entries()) {
    if (currentTime - sensorState.lastDataTime > inactiveTimeout) {
      console.log(`[AlarmWorker] 清理无活动状态: ${key}, 最后活动时间: ${new Date(sensorState.lastDataTime).toLocaleString()}`);

      // 如果是报警状态，先结束报警
      if (sensorState.isAlarming) {
        endAlarm(key);
      }

      // 删除状态记录
      sensorStates.delete(key);
    }
  }
}

/**
 * 手动清除指定报警（从UI触发）
 */
function clearSingleAlarm(deviceId: string, sensorIndex: number, gatewayIp?: string): void {
  const alarmKey = generateAlarmKey(deviceId, sensorIndex, gatewayIp);

  // 结束报警周期
  if (sensorStates.has(alarmKey)) {
    endAlarm(alarmKey);
  }

  // 从活跃报警列表移除
  activeAlarms.delete(alarmKey);

  console.log(`[AlarmWorker] 手动清除报警: ${alarmKey}`);
}

/**
 * 清除所有活跃报警
 */
function clearAllActiveAlarms(): void {
  // 结束所有报警周期
  for (const [alarmKey, sensorState] of sensorStates.entries()) {
    if (sensorState.isAlarming) {
      endAlarm(alarmKey);
    }
  }

  // 清空活跃报警列表
  activeAlarms.clear();

  console.log('[AlarmWorker] 已清除所有活跃报警');
}

/**
 * 更新设备名称映射
 */
function updateDeviceNames(deviceNames: Record<string, string>) {
  if (deviceNames && typeof deviceNames === 'object') {
    // 添加新的映射
    for (const [key, value] of Object.entries(deviceNames)) {
        moduleNameMap.set(key, value);
    }
    console.log('设备名称映射已更新:', moduleNameMap.size, '个设备');
  }
}

/**
 * 获取系统状态统计
 */
function getSystemStats(): any {
  const currentTime = Date.now();
  let activeAlarmCount = 0;
  let totalSensorCount = 0;

  for (const [key, sensorState] of sensorStates.entries()) {
    totalSensorCount++;
    if (sensorState.isAlarming) {
      activeAlarmCount++;
    }
  }

  return {
    timestamp: currentTime,
    totalSensors: totalSensorCount,
    activeAlarms: activeAlarmCount,
    voiceQueueLength: voiceQueue.length,
    isVoicePlaying: isVoicePlaying,
    alarmHistoryCount: alarmHistory.size
  };
}

// 定期清理任务
setInterval(cleanupAlarmHistory, 60 * 60 * 1000); // 每小时清理报警历史
setInterval(cleanupInactiveStates, 5 * 60 * 1000); // 每5分钟清理无活动状态

// 监听主线程消息
self.addEventListener('message', (event) => {
  const { type, data } = event.data;

  switch (type) {
    case 'process_device_status':
      // 处理设备状态数据
      if (data && typeof data === 'object') {
        // 新增：在处理数据时，也更新一下名称映射
        if (data.moduleNameMap) {
            for (const [key, value] of Object.entries(data.moduleNameMap)) {
                moduleNameMap.set(key, value as string);
            }
        }
        processDeviceStatus(data as DeviceStatus);
      }
      break;

    case 'update_config':
      // 更新报警配置
      if (data && typeof data === 'object') {
        const oldConfig = { ...alarmConfig };
        alarmConfig = { ...alarmConfig, ...data };
        // 如果总开关从开启变为关闭，则停止所有语音
        if (oldConfig.enabled && !alarmConfig.enabled) {
          stopAndClearVoice();
        }
      }
      break;

    case 'update_device_names':
   
      updateDeviceNames(data.payload);
      break;

    case 'get_active_alarms':
      // 获取当前活跃报警
      self.postMessage({
        type: 'active_alarms_response',
        data: getActiveAlarms()
      });
      break;

    case 'clear_alarm':
      // 手动清除指定报警
      if (data && data.deviceId && data.sensorIndex !== undefined) {
        clearSingleAlarm(data.deviceId, data.sensorIndex, data.gatewayIp);
        self.postMessage({
          type: 'alarm_manually_cleared',
          data: { deviceId: data.deviceId, sensorIndex: data.sensorIndex }
        });
      }
      break;

    case 'clear_single_alarm':
      if (data && data.deviceId && data.sensorIndex !== undefined) {
        clearSingleAlarm(data.deviceId, data.sensorIndex, data.gatewayIp);
      }
      break;

    case 'clear_all_alarms':
      // 清除所有活跃报警
      clearAllActiveAlarms();
      self.postMessage({
        type: 'all_alarms_cleared'
      });
      break;

    case 'voice_ended':
      // 语音播报完成回调
      isVoicePlaying = false;
      processVoiceQueue(); // 继续处理队列中的下一个消息
      break;

    case 'get_voice_queue_status':
      // 获取语音队列状态
      self.postMessage({
        type: 'voice_queue_status_response',
        data: {
          queueLength: voiceQueue.length,
          isPlaying: isVoicePlaying,
          nextMessage: voiceQueue.length > 0 ? voiceQueue[0].message : null
        }
      });
      break;

    case 'clear_voice_queue':
      // 清空并停止语音播报队列
      stopAndClearVoice();
      self.postMessage({
        type: 'voice_queue_cleared'
      });
      break;

    case 'update_voice_config':
      // 更新语音相关配置
      if (data && typeof data === 'object') {
        if (data.voiceThrottleInterval) {
          // 动态更新语音播报间隔
          const newInterval = Math.max(1000, data.voiceThrottleInterval); // 最少1秒
          Object.defineProperty(window, 'VOICE_THROTTLE_INTERVAL', { value: newInterval });
        }
        if (data.maxQueueSize) {
          // 动态更新最大队列长度
          const newMaxSize = Math.max(1, data.maxQueueSize);
          Object.defineProperty(window, 'MAX_QUEUE_SIZE', { value: newMaxSize });
        }
      }
      break;

    case 'heartbeat':
      // 心跳检测
      self.postMessage({
        type: 'heartbeat_response',
        data: {
          timestamp: Date.now(),
          activeAlarmsCount: activeAlarms.size,
          voiceQueueLength: voiceQueue.length,
          isVoicePlaying: isVoicePlaying
        }
      });
      break;

    case 'get_system_stats':
      // 获取系统状态统计
      self.postMessage({
        type: 'system_stats_response',
        data: getSystemStats()
      });
      break;

    default:
      console.warn('[AlarmWorker] 未知消息类型:', type);
  }
});

// 错误处理
self.addEventListener('error', (error) => {
  console.error('[AlarmWorker] Worker错误:', error);
  self.postMessage({
    type: 'worker_error',
    error: error.message || '未知错误'
  });
});

// Worker启动日志
console.log('[AlarmWorker] 报警处理Worker已启动');

// 导出类型定义
export type { AlarmData, DeviceStatus, AlarmConfig };